package com.csdj.rest.controller;

import com.csdj.beans.interfaces.user.IUserService;
import com.csdj.common.WsCommand;
import com.csdj.common.constant.CommonConstant;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/qrlogin")
public class WebSocketController {

    private static IUserService userService;

//    @DubboReference
    public void setUserService(IUserService userService){
        WebSocketController.userService = userService;
    }

    private Logger log = LoggerFactory.getLogger("websocket");

    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public static void sendMessage(String sessionId, WsCommand message) {
        final Session session = sessionPools.get(sessionId);
        if(session != null && session.isOpen()){
            try {
                session.getBasicRemote().sendText(message.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void sendMessage(Session session,WsCommand message){
        try {
            session.getBasicRemote().sendText(message.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session) {
        sessionPools.put(session.getId(), session);
        if(session.isOpen()) {
            try {
                session.getBasicRemote().sendText("success");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(Session session){
        sessionPools.remove(session.getId());
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message,Session session) throws IOException{
        String sessionId = session.getId();
        WsCommand cmd = WsCommand.valueOf(message);
        if(cmd != null){
            if(CommonConstant.CMD_QR_LOGIN.equals(cmd.getCmd())){
                //扫码登录请求
                final String qrLoginCode = userService.getQrLoginCode(sessionId);
                cmd.setData(qrLoginCode);
                cmd.setFrom(sessionId);
                sendMessage(sessionId,cmd);
            }
        }

    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }


}
